import { clone } from './functions/util';
import { checkCondition } from './functions/condition';
import { keyType } from './functions/define';

export class Event {
    #events: IEventData;
    constructor() { }


    initial(events: IEventData) {
        this.#events = events;
        for (const id in events) {
            const event = events[id];
            if (!event.branch) continue;
            event.branch = event.branch.map((b: any) => {
                b = b.split(':');
                b[1] = Number(b[1]);
                return b;
            });
        }
    }

    count() {
        return Object.keys(this.#events).length;
    }

    check(eventId: any, property: any) {
        const { include, exclude, NoRandom } = this.get(eventId);
        if (NoRandom) return false;
        if (exclude && checkCondition(property, exclude)) return false;
        if (include) return checkCondition(property, include);
        return true;
    }

    get(eventId: string) {
        const event = this.#events[eventId];
        if (!event) throw new Error(`[ERROR] No Event[${eventId}]`);
        return clone(event);
    }

    information(eventId: string) {
        const { event: description } = this.get(eventId)
        return { description };
    }

    do(eventId: string, property: any) {
        const { effect, branch, event: description, postEvent } = this.get(eventId);
        if (branch)
            for (const [cond, next] of branch)
                if (checkCondition(property, cond))
                    return { effect, next, description };
        return { effect, postEvent, description };
    }

}

type IEventData = {
    [key: string]: {
        id: number,
        event: string,
        NoRandom?: number,
        exclude?: string,
        effect: {
            [key in keyType]: number
        },
        branch: string[]
    }
};